package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;



    @Transactional
    public void newDishes(DishDTO dishDTO){
        //菜品已存在
        Dish dish = dishMapper.getByDishName(dishDTO.getName());
        if (dish!=null) {
            throw new BaseException(dish.getName()+MessageConstant.ALREADY_EXIST);
        }

        //包装菜品参数
        Dish container = new Dish();
        BeanUtils.copyProperties(dishDTO,container);

        //添加菜品
        dishMapper.insert(container);

        //获取插入后菜品的主键
        Long dishId = container.getId();
        log.info("菜品id为:{}",dishId);

        //添加菜品口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && !flavors.isEmpty()){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorMapper.batchInsert(dishDTO.getFlavors());
        }




    }

    @Override
    public PageResult page(DishPageQueryDTO dto) {
        //启动分页查询
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> data =dishMapper.pageQuery(dto);

        // 查询的数据
        List<DishVO> result = data.getResult();
        // 总页数
        long total = data.getTotal();
        return new PageResult(total,result);
    }

    @Override
    public void startOrStop(Long id,Integer status) {
        Dish dish = Dish.builder().id(id).status(status).build();
        dishMapper.update(dish);
    }

    /**
     * 通过id批量删除菜品
     */
    @Transactional
    @Override
    public void deleteBatchDish(List<Long> ids) {
        //判断菜品状态 起售则不能删除
        List<Dish> dishData = dishMapper.queryByIds(ids);
        dishData.forEach(dish -> {
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //判断菜品是否在套餐中
        List<Long> sid = setmealDishMapper.querySetmealIdbyDishID(ids);
        if(!sid.isEmpty()){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //菜品进行删除
        dishMapper.deleteBatch(ids);

        //菜品的风味进行删除
        dishFlavorMapper.deleteBatch(ids);


    }

    /**
     * 通过菜品id 查找菜品相关的内容
     * @param dishId
     * @return
     */
    @Override
    public DishVO queryDishById(Long dishId) {
        DishVO dishVO = new DishVO();
        //查询菜品信息
        Dish dish = dishMapper.queryById(dishId);
        BeanUtils.copyProperties(dish,dishVO);
        //查询分类名称进行封装VO
//        Category category = categoryMapper.queryByCategoryId(dish.getCategoryId());
//        dishVO.setCategoryName(category.getName());
        //菜品风味进行查询并封装到VO
        List<DishFlavor> dishFlavors = dishFlavorMapper.queryByDishId(dishId);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 更新菜品表和菜品风味数据
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        //更新菜品数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //菜品风味添加
        dishDTO.getFlavors().forEach(dishFlavor -> {
            Long id = dishFlavor.getId();
            // 菜品风味id 如果不存在则添加数据

        });




        //更新菜品风味数据
        dishFlavorMapper.updateBatch(dishDTO.getFlavors());


    }


    /**
     * 更新菜品基本信息和菜品风味
     * @param dishDTO
     */
    @Transactional
    public void updateDishWithFlavor(DishDTO dishDTO) {
        //菜品基本信息更新
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        //菜品风味更新
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors !=null && !flavors.isEmpty()){
            //删除原有风味
            dishFlavorMapper.deleteByDishId(dishDTO.getId());
            //更新菜品的风味
            dishFlavorMapper.batchInsert(flavors);
        }

    }


    /**
     * 查找菜品通过分类id
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> queryDishByCategoryId(String categoryId) {
        List<Dish> list = dishMapper.queryByCategoryId(Long.valueOf(categoryId));
        return list;
    }


    /**
     * 通过分类id 查询启用菜单数据
     * @param categoryId
     * @return
     */
    public List<Dish> listByActiveCategoryId(Long categoryId) {
        List<Dish> activeLists = dishMapper.selectActiveByCategoryId(categoryId);
        return activeLists;
    }

    /**
     * 通过菜品id查询菜品
     * @param dishId
     * @return
     */
    @Override
    public Dish getById(Long dishId) {
        return dishMapper.selectById(dishId);
    }


}
